using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

public class EditorConfigGenerator : EditorWindow {
    private string[] variableTypes = { "int", "float", "uint", "string" };
    private string mConfigName;
    private List<int> mVariableTypeList = new();
    private List<string> mVariableNameList = new();

    private string mSelectedDirectory = "No Directory";
    [MenuItem("Tools/ConfigGenerator")]
    public static void ShowWindow() {
        EditorWindow window = EditorWindow.GetWindow(typeof(EditorConfigGenerator),false,"Config Generator");
    }

    private void OnGUI() {
        //风格设置
        EditorStyles.label.fontSize = 14;
        EditorStyles.textField.fontSize = 14;
        
        GUILayout.BeginVertical(GUILayout.ExpandWidth(true),GUILayout.ExpandHeight(true));
        GUILayout.Label("Config Generator",EditorStyles.boldLabel);

        //数据设置
        mConfigName = EditorGUILayout.TextField("Config Name:", mConfigName);
        
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Select Directory"))
        {
            selectDirectory();
        }
        GUILayout.Label(mSelectedDirectory,EditorStyles.boldLabel);
        GUILayout.EndHorizontal();

        for (int i = 0; i < mVariableTypeList.Count;++i) {
            GUILayout.BeginHorizontal();
            mVariableTypeList[i] = EditorGUILayout.Popup("VariableType", mVariableTypeList[i],variableTypes);
            mVariableNameList[i] = EditorGUILayout.TextField("VariableName", mVariableNameList[i]);

            if (GUILayout.Button("X")) {
                mVariableTypeList.RemoveAt(i);
                mVariableNameList.RemoveAt(i);
            }
            GUILayout.EndHorizontal();
        }

        if (GUILayout.Button("Add")) {
            mVariableTypeList.Add(0);
            mVariableNameList.Add("");
        }
        
        
        if (GUILayout.Button("Generate")) {
            generateConfig();
        }  
        GUILayout.EndVertical();
    }

    private void selectDirectory() {
        // 打开目录选择面板
        string directoryPath = EditorUtility.OpenFolderPanel("Select Directory", "", "");

        // 如果用户选择了目录，则更新文本框中的内容
        if (!string.IsNullOrEmpty(directoryPath))
        {
            mSelectedDirectory = directoryPath;
        }
    }
    
    private void generateConfig() {
        if (!checkConfig()) {
            return;
        }
        StringBuilder builder = new StringBuilder();

        builder.Append      ("namespace Core.CSV {\n");
        builder.AppendFormat("    public class TB{0}Interface : TBBaseInterface, IFileReader {{\n",mConfigName);
        builder.Append      ("        public string FileName {\n");
        builder.AppendFormat("            get {{ return \"{0}.csv\"; }}\n", mConfigName);
        builder.Append      ("        }\n");
        builder.Append      ("        public override void AddData(params object[] p) {\n"); 
        builder.AppendFormat("            mDic.Add((uint)p[0], new TB{0}Config(p));\n");
        builder.Append      ("        }\n");
        builder.Append      ("    }\n");
        builder.AppendFormat("    public class TB{0}Config : TBBaseConfig {{\n",mConfigName);
        builder.AppendFormat("        public TB{0}Config(params object[] p) {{\n",mConfigName);
        for (int i = 0; i < mVariableTypeList.Count; ++i) {
            builder.AppendFormat("            {0} = ({1})p[{2}];\n",mVariableNameList[i],variableTypes[mVariableTypeList[i]],i);
        }
        builder.Append      ("        }\n");
        for (int i = 0; i < mVariableTypeList.Count; ++i) {
            builder.AppendFormat("        public {0} {1};\n", variableTypes[mVariableTypeList[i]], mVariableNameList[i]);
        }
        builder.Append      ("    }\n");
        builder.Append      ("}\n");
        
        saveAsFile(builder.ToString());
    }

    private bool checkConfig() {
        bool res = mConfigName != "" && mSelectedDirectory != "No Directory";
        for (int i = 0; i < mVariableNameList.Count; ++i) {
            if (mVariableNameList[i] == "") {
                res = false;
            }
        }

        if (!res) {
            EditorUtility.DisplayDialog("错误", "文件信息不符合要求，请重新输入！", "OK");
        }
        
        return res;
    }
    
    private void saveAsFile(string data) {
        string filePath = string.Concat(mSelectedDirectory, "/TB", mConfigName, ".cs");
        try {
            File.WriteAllText(filePath, data);
        } catch (Exception ex) {
            Debug.LogErrorFormat("保存文件:{0}失败",filePath);
        }
    }
}
